package cn.com.winning.ecare.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.winning.ecare.activity.HospitalDq.MyAdapter;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.URLUtils;
import cn.com.winning.ecare.widgets.CustomProgressDialog;

/**医院选择
 * @author Administrator
 *
 */
public class HospitalYy extends Activity {
	private ImageButton ks_preview = null;
	private ListView lv = null;

	private CustomProgressDialog proDialog;// 加载框
	private HospitalYy oThis = this;

	private Intent mIntent = null;
	private Map<String, Object> map_yy; // 医院map
	List<Map<String, Object>> list_yy = new ArrayList<Map<String, Object>>();// 医院list
	MyApplication myApp;

	private int preID = -1;
	private MyAdapter myAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(R.layout.hostital_yy);
		myApp = (MyApplication) getApplication();
		myApp.addActivity(this);
		// 确定view
		findView();

		// 初始化界面数据
		GetData();

		// 点击事件
		setOnClick();
	}

	private void GetData() {
		proDialog = CustomProgressDialog.createDialog(oThis);
		proDialog.setMessage("数据加载中...");
		proDialog.show();
		proDialog.setCanceledOnTouchOutside(false);
		// 这里单开一个线程和后台数据交互
		new Thread(new LoadData()).start();

	}

	class LoadData implements Runnable {

		public void run() {
			// TODO Auto-generated method stub
			Looper.prepare();
			iniData();
			Looper.loop();
		}
	}

	private void iniData() {
		try {
			Message msg = myHandler.obtainMessage();
			List<NameValuePair> ls = new ArrayList<NameValuePair>();
			ls.add(new BasicNameValuePair("orgid", getIntent().getStringExtra("dq_id")));
			JSONObject json = HTTPGetTool.getTool().post(
					URLUtils.HOSTMAIN + URLUtils.GETYYLIST, ls);
			JSONArray jsonArr;
			if (json != null && !json.equals("")) {
				if (!json.toString().equals("{\"msg\":\"系统错误！\",\"success\":\"false\"}"))
				{
					if (json.getString("yyinfo").length() > 0)
					{
						// 获取地区信息
						jsonArr = new JSONArray(json.getString("yyinfo"));
						JSONObject js = null;
						for (int i = 0; i < jsonArr.length(); i++) {
							map_yy = new HashMap<String, Object>();
							js = jsonArr.getJSONObject(i);
							// previewId = js.getString("PId");
							map_yy.put("id", js.getString("id"));
							map_yy.put("yydm", js.getString("yydm"));
							map_yy.put("yymc", js.getString("yymc"));
							list_yy.add(map_yy);
						}

						msg.what = 0;
						msg.obj = list_yy;
					}else
					{
						msg.what = -1;
						msg.obj = "暂无数据";
					}
				}
				else
				{
					msg.what = -1;
					msg.obj = "系统错误";
				}
	
			}
			else
			{
				msg.what = -1;
				msg.obj = "网络连接错误！";
			}
			myHandler.sendMessage(msg);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 主线程状态更新
	 */
	Handler myHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				case -1:
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					Toast.makeText(oThis, (String) msg.obj, Toast.LENGTH_SHORT).show();
					break;
				case 0:
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					list_yy = (List<Map<String, Object>>) msg.obj;
					if (myAdapter == null)
					{
						myAdapter = new MyAdapter(oThis);
					}
					myAdapter.setList(list_yy);
					lv.setAdapter(myAdapter);
					myAdapter.notifyDataSetChanged();
					
					break;
				default:
					break;
			}
		};
	};


	class MyAdapter extends BaseAdapter {
		private List<Map<String, Object>> list;
		private LayoutInflater mLayoutInflater;

		MyAdapter(Context context) {
			mLayoutInflater = LayoutInflater.from(context);
		}

		public List<Map<String, Object>> getList() {
			return list;
		}

		public void setList(List<Map<String, Object>> list) {
			this.list = list;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = mLayoutInflater.inflate(
						R.layout.hospital_yy_item, null);
				holder = new ViewHolder();
				holder.tv_id = (TextView) convertView.findViewById(R.id.yy_id);
				holder.tv_mc = (TextView) convertView.findViewById(R.id.yy_mc);
				holder.tv_yyid = (TextView) convertView.findViewById(R.id.yyid);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.tv_id.setText((CharSequence) list.get(position).get("yydm"));
			holder.tv_mc.setText((CharSequence) list.get(position).get("yymc"));
			holder.tv_yyid.setText((CharSequence) list.get(position).get("id"));
			
			if(position%2==0){//偶数
				if (position == preID)
					convertView.setBackgroundColor(getResources().getColor(
    						R.color.listhead_color));
    			else
    				convertView.setBackgroundColor(getResources().getColor(
    						R.color.backgroundMYD));
            }else{//奇数
            	if (position == preID)//选中
            		convertView.setBackgroundColor(getResources().getColor(
							R.color.listhead_color));
				else
					convertView.setBackgroundColor(getResources().getColor(
							R.color.white_bg));
            }
			return convertView;
		}

	}

	public class ViewHolder {
		private TextView tv_id;
		private TextView tv_mc;
		private TextView tv_yyid;
	}

	private void setOnClick() {
		// 设置preview监听
		ks_preview.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				Intent intent = getIntent();
				HospitalYy.this.setResult(0, intent);// 跳转回原来的activity   
				HospitalYy.this.finish();// 一定要结束当前activity   

			}
		});

		// 设置下一级菜单
		lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				myAdapter.notifyDataSetChanged();
				TextView yy_mc = (TextView) arg1.findViewById(R.id.yy_mc);
				TextView yy_id = (TextView) arg1.findViewById(R.id.yy_id);//医院编码
				TextView yy_yyid = (TextView) arg1.findViewById(R.id.yyid);//医院id
				
				if(myApp.getServiceManager()!=null){
					myApp.getServiceManager().stopThread();
					myApp.getServiceManager().stopService();
				}
				
				Intent intent = getIntent();
				intent.putExtra("yy_mc", yy_mc.getText().toString());
				intent.putExtra("yy_id", yy_id.getText().toString());
				intent.putExtra("yy_yyid", yy_yyid.getText().toString());
				preID = arg2;
				HospitalYy.this.setResult(0, intent);// 跳转回原来的activity   
				HospitalYy.this.finish();// 一定要结束当前activity   
			}
		});
	}

	private void findView() {
		mIntent = getIntent();
		lv = (ListView) this.findViewById(R.id.yy_list);
		ks_preview = (ImageButton) this.findViewById(R.id.yy_preview);
	}
	
	@Override
	    public boolean onKeyDown(int keyCode, KeyEvent event) {
	        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
	        	Intent intent = getIntent();
				HospitalYy.this.setResult(0, intent);// 跳转回原来的activity   
				HospitalYy.this.finish();// 一定要结束当前activity   
	            return false;
	        }
	        return false;
	    }

}
